<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of subtaskModelClass
 *
 * @author nstevens
 */
include_once 'mysql/dbHelper.php';
include_once 'classes/financialClass.php';
include_once 'classes/subtaskDependency.php';
include_once 'model/commonModel.php';

class subtaskModelClass extends commonModel {

    public $taskID, $parameterID, $paramName, $reqName, $reqPriority, $reqID, $category, $deliverable, $percentComplete;
    public $subtaskId, $projectID, $fy;
    //array
    public $financialObject, $notes, $dependencies, $subtaskLabor;

    public function __construct() {
        
    }

    public function init($row) {
        $this->title = $row['title'];
        $this->wbsID = $row['wbsID'];
        $this->wbsString = getWbsString($this->wbsID);
        $this->startDate = $row['startDate'];
        $this->endDate = $row['endDate'];
        $this->ID = $row['subtaskID'];
        $this->taskID = $row['taskID'];
        $this->projectID = getFieldGivenAnID("task", "taskID", $this->taskID, "projectID");
        $this->projectStatus = getFieldGivenAnID('project', "projectID", $this->projectID, "status");
        $this->projectStartDate = getFieldGivenAnID('project', "projectID", $this->projectID, "startDate");
        $this->projectEndDate = getFieldGivenAnID('project', "projectID", $this->projectID, "endDate");
        $this->fy = getFieldGivenAnID('project', "projectID", $this->projectID, "fy");
        //$this->parameterID = $row['parameterID'];
        //$this->paramName = getFieldGivenAnID("parameter", "parameterID", $this->parameterID, "name");
        //$this->reqID = $row['reqID'];
        //$this->reqName = getFieldGivenAnID("requirement", "reqID", $this->reqID, "description");
        //$this->reqPriority = getFieldGivenAnID("requirement", "reqID", $this->reqID, "priority");
        $this->category = $row['category'];
        $this->deliverable = $row['deliverable'];
        $this->status = $row['status'];
        $this->duration = $row['duration'];
        $this->description = $row['description'];
        $this->proposedCost = $row['proposedCost'];
        $this->percentComplete = $row['percentComplete'];
        $this->notes = $this->getAllNotes();
        //model
        //$this->subtaskModel = new subtaskModelClass($this->taskID, $this->ID);
        $this->financialObject = $this->getSubtaskFinancials();
        $this->dependencies = $this->getDependencies();
        //$this->subtaskLabor = $this->getSubtaskLabor();
    }

    public function init2($subtaskID) {
        $subtaskResult = executeSelect("SELECT * FROM subtask WHERE subtaskID=$subtaskID");
        $row = mysqli_fetch_array($subtaskResult);
        $this->init($row);
    }

    function getSubtasksFinancialsTable() {
        $output = "";
        $output .= '<table class="width100" cellspacing="1">';
        $output .= '<col width="15%"><col width="15%"><col width="5%"><col width="4%"><col width="4%">';
        $output .= '<caption>Subtask Status</caption>';
        $output .= commonModel::getFinancialTableHeader();

        $output .= ' <tr>';
        if (isPI()) {
            $text = '% Complete: ' . getFormInputElement("text", "textFieldPercentComplete", '30px', $this->percentComplete);
            $output .= $this->getTD($text, "grey", NULL, 'colspan="3"');
        } else {
            $output .= '  <td rowspan="1">% Complete: ' . $this->percentComplete . '</td>';
        }
        //$output .= '<td colspan="2" rowspan="2" class = "td2">' . $this->title . '</td><td>-</td><td>-</td>';
        $actualCost = $this->financialObject->actualDollars;
        $actualHours = $this->financialObject->actualDuration;
        $proposedCost = $this->financialObject->curYearDollars;
        $proposedHours = $this->financialObject->curYearDuration;
        $output .= '  <td></td><td></td><td>C</td><td>T</td><td>D</td><td>R</td><td>P</td>';
        $output .= "  <td>$proposedHours[0]</td><td>$proposedHours[1]</td><td>$proposedHours[2]</td><td>$proposedHours[3]</td>";
        $output .= "  <td>$proposedCost[0]</td><td>$proposedCost[1]</td><td>$proposedCost[2]</td><td>$proposedCost[3]</td>";
        $output .= '  <td></td><td></td>';
        $output .= ' </tr>';
        $output .= ' <tr class="grey">';
        if (isPI()) {
            $text = 'Status: ' . getDropDownMenu(getTaskStatusArray(), 'subtaskStatusDropdown', $this->status, NULL, NULL, 'subtaskStatusDropdown') . getHiddenField('origStatus', $this->status, 'origStatusId');
            $output .= $this->getTD($text, NULL, NULL, 'colspan="3"');
        } else {
            $output .= ' <td>Status: ' . $this->status . '</td>';
        }
        $output .= '  <td></td><td></td>';
        $output .= '  <td>C</td><td>T</td><td>D</td><td>R</td><td>A</td>';
        if (isPI()) {
            for ($i = 0; $i < 4; $i++) {
                $output .= $this->getTD(getFormInputElement("text", "textFieldHours$i", '20px', $actualHours[$i]));
            }
            for ($i = 0; $i < 4; $i++) {
                $output .= $this->getTD(getFormInputElement("text", "textFieldCost$i", '20px', $actualCost[$i]));
            }
        } else {
            $output .= "  <td>$actualHours[0]</td><td>$actualHours[1]</td><td>$actualHours[2]</td><td>$actualHours[3]</td>";
            $output .= "  <td>$actualCost[0]</td><td>$actualCost[1]</td><td>$actualCost[2]</td><td>$actualCost[3]</td>";
        }
        $output .= '  <td></td><td></td>';
        $output .= ' </tr>';
        if (isPI()) {
            $output .= ' <tr class ="fieldLabel">';
            $output .= $this->getTD('Comments: ' . getFormInputElement("text", "textFieldComments", "80%"), NULL, NULL, 'colspan="3"');
            $output .= '<td colspan="17"></td>';
            $output .= ' </tr>';
            $output .= ' <tr class ="fieldLabel">';
            $output .= '  <td colspan="20">' . getFormInputElement("submit", "submit", NULL, "Submit Subtask Updates") . ' </td>';
            $output .= ' </tr>';
        }
        $output .= ' </table>';
        return $output;
    }

    //HTML**********************************************************************
    public function getSubtaskDetailsPage() {
        $output = "";
        $output .= $this->getBasicHeader("Subtask Details");
        //$output .= getUpToMainMenu(getUserRole(), "Subtask Details");
        $output .= '<br>';
        $output .= '<a href="mainPage.php?request=project&action=viewProjectDetails&projectId=' . $this->projectID . '">Back to Project</a> --> ';
        $output .= '<a href="mainPage.php?request=task&action=viewTaskDetails&projectId=' . $this->projectID . '&taskId=' . $this->taskID . '">Back to Task</a>';

        //display any flags
        if (isset($_GET['update'])) {
            $output .= $this->getFlagUnorderedList($_GET['update']);
        }
        $output .= '<br>';
        //DETAILS***************************************************************
        $output .= $this->getSubtaskDetailsForm();
        $output .= '<br><br><hr><br>';
//        $output .= $this->getUpdateSubtaskForm();
//        $output .= '<br><br><hr><br>';
        //FINANCIALS************************************************************
        if (isProjectInApprovedState(getStatus('project', $this->projectID)) && !(strcmp(getStatus('project', $this->projectID), 'submitComplete') === 0)) {
            $output .= getFormLinePostWithOnSubmit("statusForm", "mainPage.php?request=subtask&action=processExistingSubtaskRequest", 'validateSubtaskUpdate(this)');
            $output .= $this->getSubtasksFinancialsTable();
            $output .= getHiddenField("subtaskId", $this->ID);
            $output .= '</form>';
            $output .= '<br><br><hr><br>';
        }

        //GET FEEDBACK**********************************************************
        $projectStatus = getStatus('project', $this->projectID);
        if (!isProjectInApprovedState($projectStatus) || strcmp($projectStatus, 'submitComplete') === 0) {
            $output .= $this->getNotesFormFromObject($this->getNotes('Feedback'), NULL, 'Feedback');
        }
        if (!isPI()) {
            $output .= $this->getNotesFormFromObject($this->getNotes('Reviewer Notes'), NULL, 'Reviewer Notes');
        }
        $output .= $this->getNotesFormFromObject($this->getNotes('PI Notes'), NULL, 'PI Notes');
        //empty task notes form
        //$output .= $this->getNotesForm($this->wbsID, "PI Notes");
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        return $output;
    }

    function getSubtaskDetailsTable() {
        $statusBGcolor = getStatusBackgroundColor($this->status, 'task');
        $output = "";
        $output .= '<table class="width100" cellspacing="1">';
        $output .= '<caption>Sub Task Details</caption>';

        //Row 1 WBS, title, description
        $output .= ' <tr class ="header">';
        $output .= '     <td>WBS</td>';
        $output .= '     <td colspan="2">Title</td>';
        $output .= '     <td colspan="5">Description</td>';
        $output .= ' </tr>';

        $output .= ' <tr class="field">';
        $output .= ' <td>' . $this->wbsString . ' </td>';
        $output .= ' <td colspan="2">' . $this->title . ' </td>';
        $output .= ' <td colspan="5">' . $this->description . '</td>';
        $output .= ' </tr>';

        //row 2 Requirement, Parameter, Start, End, Duration, Cost, Status
        $output .= ' <tr class ="header">';
        $output .= '     <td>Parameter</td>';
        $output .= '     <td colspan="2">Requirement</td>';
        $output .= '     <td>Start</td>';
        $output .= '     <td>End</td>';
        $output .= '     <td>Effort (hours)</td>';
        $output .= '     <td>Cost</td>';
        $output .= '     <td>Status</td>';
        $output .= ' </tr>';

        $output .= ' <tr class="field">';
        $output .= ' <td>' . getParameterNameFromID($this->parameterID) . ' </td>';
        $output .= ' <td colspan="2">' . getRequirementNameFromID($this->reqID) . ' </td>';
        $output .= ' <td>' . $this->startDate . ' </td>';
        $output .= ' <td>' . $this->endDate . ' </td>';
        $output .= ' <td>' . $this->duration . ' </td>';
        $output .= ' <td>' . $this->proposedCost . ' </td>';
        $output .= " <td bgcolor = \"$statusBGcolor\">$this->status</td>";
        $output .= ' </tr>';
        return $output;
    }

    function getSubtaskDetailsForm() {
        $output = "";
        $output .= getFormLinePost("subtaskDetailsForm", "mainPage.php?request=subtask&action=processExistingSubtaskRequest");
        $output .= $this->getSubtaskDetailsTable();
        $output .= ' <tr class ="fieldLabel">';

        if (strcmp(getUserRole(), "pi") === 0) {
            if (strcmp($this->projectStatus, "piReview") === 0 || strcmp($this->projectStatus, "submitComplete") === 0) {
                //if piReview no options
                $output .= ' <td colspan="8">Submitted to PI reviewer</td>';
            }
            //any active status we chould give the option to change the status
            else if (strcmp($this->projectStatus, "approvalFinal") === 0) {
//                $output .= ' <td colspan="1">' . getFormInputElement("submit", "submit", NULL, "Change Status") . ' </td>';
//                $output .= ' <td colspan="1">Status ' . getDropDownMenu(getTaskStatusArray(), 'subtaskStatusDropdown', $this->status) . ' </td>';
//                $output .= ' <td colspan="6"></td></tr>';
//                $output .= ' <tr class ="fieldLabel">';
//                $output .= '  <td colspan="1">' . getFormInputElement("submit", "submit", NULL, "Update Financials") . ' </td>';
//                $output .= '  <td colspan="1">Quarter ' . getDropDownMenu($this->getValidQuarters(), 'subtaskQuarterDropdown', $this->status) . '  ';
//                $output .= '   Type ' . getDropDownMenu(array("cost", "hours"), 'subtaskTypeDropdown', $this->status) . ' ';
//                $output .= '   Value ' . getFormInputElement("text", "textFieldFinancial") . ' ($ in K)</td>';
//                $output .= ' <td colspan="6"></td></tr>';
//                $output .= ' <tr class ="fieldLabel">';
//                $output .= '  <td colspan="1">' . getFormInputElement("submit", "submit", NULL, "Update Percent Complete") . ' </td>';
//                $output .= '  <td> Value ' . getFormInputElement("text", "textFieldPercentComplete") . '</td>';
//                $output .= ' <td colspan="6"></td></tr>';
//                $output .= ' <tr class ="fieldLabel">';
//                $output .= '  <td colspan="1">' . getFormInputElement("submit", "submit", NULL, "Submit Quarterly Progress") . ' </td>';
//                $output .= '  <td colspan="12"> Progress Report ' . getTextArea("quarterlyProgressTextarea", 500) . '</td>';
//                $output .= ' </tr>';
            } else {
                $output .= ' <td >';
                $output .= getFormInputElement("submit", "submit", NULL, "Edit Subtask");
                $output .= ' </td>';
                $output .= ' <td colspan="7">';
                $output .= getFormInputElement("submit", "submit", NULL, "Delete Subtask");
                $output .= ' </td>';
            }
        }
        //PRINCIPAL INVESTIGATOR REVIEWER
        if (strcmp(getUserRole(), "pireviewer") === 0) {
            if (strcmp($this->projectStatus, "submitComplete") === 0) {
                //if pi review then allow feedback
                $output .= ' <td>';
                $output .= getHiddenField("wbsID", $this->wbsID);
                $output .= getFormInputElement("submit", "submit", NULL, "Add Notes");
                $output .= ' </td>';
                $output .= ' <td>' . getDropDownMenuText(getNotesTypeArray(), "notesTypeDropdown") . '</td>';
                $output .= ' <td colspan="7">';
                $output .= getFormInputElement("text", "textFieldNotes", "99%");
                $output .= ' </td>';
            } else if (strcmp($this->projectStatus, "piFeedback") === 0) {
                $output .= ' <td colspan="8">Awaiting feedback from PI</td>';
            } else if (strcmp($this->projectStatus, "piApproverSubmit") === 0) {
                $output .= ' <td colspan="8">Awaiting Approval from Approver</td>';
            }
        }
        $output .= '      <input type="hidden" name="subtaskId" value="' . $this->ID . '">';
        $output .= '      <input type="hidden" name="taskId" value="' . $this->taskID . '">';
        $output .= '      <input type="hidden" name="projectID" value="' . $this->projectID . '">';
        $output .= '      <input type="hidden" name="projectStartDate" value="' . $this->projectStartDate . '">';
        $output .= '      <input type="hidden" name="projectEndDate" value="' . $this->projectEndDate . '">';
        $output .= getCloseTag("table");
        $output .= getCloseTag("form");
        return $output;
    }

    protected function getUpdateSubtaskForm() {
        $output = "";
        $output .= $this->getRequiredFieldText();
        $output .= getFormLinePost("subtaskDetailsForm", "mainPage.php?request=subtask&action=processExistingSubtaskRequest");
        $output .= '<table class="width40Center" cellspacing="1">';
        $output .= '<caption>Subtask Update</caption>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= ' <td colspan="1">Status</td>';
        $output .= ' <td colspan="1">' . getDropDownMenu(getTaskStatusArray(), 'subtaskStatusDropdown', $this->status) . '</td>';
        $output .= ' </tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '  <td colspan="1">Percent Complete</td>';
        $output .= '  <td>' . getFormInputElement("text", "textFieldPercentComplete") . '</td>';
        $output .= ' </tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '  <td colspan="1">Financials</td>';
        $output .= '  <td colspan="1">';
        $output .= '<table class="width100" cellspacing="1">';
        $output .= ' <tr class ="fieldLabel"><td colspan="4">Hours</td><td colspan="4">Dollars</td></tr>';
        $output .= ' <tr><td>Q1</td><td>Q2</td><td>Q3</td><td>Q4</td><td>Q1</td><td>Q2</td><td>Q3</td><td>Q4</td>';
        $output .= '</table>';
        $output .= '</td>';

        $output .= ' <tr class ="fieldLabel">';
        $output .= '  <td colspan="2">' . getFormInputElement("submit", "submit", NULL, "Submit Subtask Updates") . ' </td>';
        $output .= ' </tr>';
        $output .= '</table></form>';
        return $output;
    }

    protected function getValidQuarters() {
        $array = array();
        for ($i = 0; $i < 4; $i++) {
            if ($this->financialObject) {
                if (strcmp($this->financialObject->curYearDollars[$i], "0") !== 0) {
                    array_push($array, ($i + 1));
                }
            }
        }
        return $array;
    }

    public function changeSubtaskStatus() {
        $newStatus = $_POST['subtaskStatusDropdown'];
        $subtaskId = $_POST['subtaskId'];
        $sqlInsert = "UPDATE subtask SET status='$newStatus' WHERE subtaskId=$subtaskId";
        $result = executeUpdate($sqlInsert);
        if ($result) {
            $url = $_SERVER['HTTP_REFERER'];
            return "location:$url";
        } else {
            return NULL;
        }
    }

    /**
     * Gets the html table of the subtasks contained in the given result resource.
     * @param type $result the result resource related to a unique taskID from the db (contains 1 or more rows)
     */
    function getSubtasksSummaryTable($result, $taskId, $projectID, $projectStartDate, $projectEndDate) {
        echo '<table class="width100" cellspacing="1">';
        echo '<caption>Sub Tasks</caption>';
        echo ' <tr class ="header">';
        echo '     <td>WBS</td>';
        echo '     <td>Title</td>';
        echo '     <td>Requirement</td>';
        echo '     <td>Parameter</td>';
        echo '     <td>Duration</td>';
        echo '     <td>Start Date</td>';
        echo '     <td>End Date</td>';
        echo '     <td>Cost</td>';
        echo '     <td>Status</td>';
        echo ' </tr>';
        while ($row = mysqli_fetch_assoc($result)) {
            $subtaskID = $row['subtaskID'];
            $title = $row['title'];
            $description = $row['description'];
            $reqID = $row['reqID'];
            $paramID = $row['parameterID'];
            $duration = $row['duration'];
            $proposedCost = $row['proposedCost'];
            $start = $row['startDate'];
            $end = $row['endDate'];
            $wbsId = $row['wbsID'];
            $wbsString = getFieldGivenAnID("wbs", "wbsID", $wbsId, "wbsString");
            $status = $row['status'];
            $statusBGcolor = getStatusBackgroundColor($status, 'task');

// echo $reqDescription.'<br>';
            echo ' <tr class="field">';
            echo ' <td>';
            echo '<a class="black" href="subtaskController.php?projectId=' . $projectID . '&taskId=' . $taskId . '&subtaskId=' . $subtaskID . '&start=' . $projectStartDate . '&end=' . $projectEndDate . '">' . $wbsString . '</a>';
            echo ' </td>';
            echo ' <td>' . $title . '</td>';
            //echo ' <td>' . $description . ' </td>';
            echo ' <td>';
            echo getRequirementNameFromID($reqID);
            echo ' </td>';
            echo ' <td>';
            echo getParameterNameFromID($paramID);
            echo ' </td>';
            echo ' <td>' . $duration . '</td>';
            echo ' <td>' . $start . '</td>';
            echo ' <td>' . $end . '</td>';
            echo ' <td>' . $proposedCost . '</td>';
            echo " <td bgcolor = \"$statusBGcolor\">$status</td>";
            echo ' </tr>';
        }
    }

    public function getEditSubtaskPage() {
        $start = $_POST['projectStartDate'];
        $end = $_POST['projectEndDate'];
        $output = "";
        $output .= $this->getBasicHeader("Edit Subtask", false, false, $start, $end);
        $output .= commonModel::getSubtaskForm($this);
        $output .= '<br><br> ' . getWebmasterFeedbackForm();
        return $output;
    }

    function getEditSubtaskFormQuarterly() {
        $output = "";
        $commentsTextFieldString = getFormInputElementText("text", "commentsTextField", "98%", NULL, NULL, 'commentsTextField');
        $depAddButtonText = getFormInputElementText("button", "depAddButton", "98%", "Add Dependency", "addDependencyRow()");
        $caption = '<caption>Edit Subtask</caption>';
        $dependencyDropdownString = getDependencyDropdownText($this->projectID, $this->ID);
        $reqDropdownString = getGenericDropdownMenuText(getRequirements($this->fy, true), "reqDropdown", NULL, false, NULL, NULL, $this->reqID, NULL, NULL, true); //, "getParametersFromReq(this.value)", "reqDropdown", $this->reqID);
        $categoryDropdownString = getDropDownMenuText(getSubtaskCatergoryArray(), "dropdownCategory", $this->category);
        $deliverableTextfieldString = getFormInputElementText("text", "deliverableTextField", "98%", $this->deliverable);
        $parameterDropdownString = getGenericDropdownMenuText(executeSelect("SELECT * FROM parameter ORDER by name"), "dropdownParameter", "97%", false, NULL, NULL, $this->parameterID);
        //$parameterDropdownString = getParametersFromReqText($this->reqID, true, "getSatFromParameter(this.value)", getParameterNameFromID($this->parameterID));
        $titleString = getFormInputElementText("text", 'titleTextField', '98%', $this->title);
        $descriptionTextFieldString = getFormInputElementText("text", 'descriptionTextField', '98%', $this->description, NULL, 'descriptionTextfield');

        $startDateTextFieldString = getFormInputElementText("text", "startDateTextField", NULL, getDatePickerFormat($this->startDate), NULL, "from");
        $endDateTextFieldString = getFormInputElementText("text", "endDateTextField", NULL, getDatePickerFormat($this->endDate), NULL, "to");
        $durationTextFieldString = getFormInputElementText("text", "durationTextField", '98%', $this->duration, NULL, 'duration');
        $costTextFieldString = getFormInputElementText("text", "costTextField", '98%', $this->proposedCost, "getRate()", 'cost');
        $rate = round($this->proposedCost / $this->duration);
        $submitButtonString = getFormInputElementText("submit", "submit", NULL, "Save Subtask");

        $output .= getFormLinePostWithOnSubmit("createSubtaskForm", "mainPage.php?request=subtask&action=processEditSubtaskSubmit&taskId=$this->ID&projectId=$this->projectID", " validateSubtask(this)");
        //getFormLinePostWithOnSubmit("createSubtaskForm", "subtaskController.php");
        //getStartFormLinePostWithOnSubmit("createSubtaskForm", "test.php", " validateSubtask(this)");
        //Table Start***************************************************************
        $output .= '<table class="width100" cellspacing="1">';
        $colWidth = 100 / 10;
        $output .= '<col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%">';
        $output .= $caption;
        $output .= ' <tr class="row-category"><td class="col-2" colspan="10">Subtask Description</td></tr>';

        //Section 1 Title, Description**********************************************
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="3">Title</td>';
        $output .= '     <td colspan="7">Description</td>';
        $output .= ' </tr>';

        $output .= ' <tr>';
        $output .= '     <td class="col-2" colspan="3">';
        $output .= $titleString;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="7">';
        $output .= $descriptionTextFieldString;
        $output .= '     </td>';
        $output .= ' </tr>';

        //Section 2  Req, Parameter, Category, Deliverable**************************
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="10">Requirement (Ordered By Priority)</td>';
        $output .= ' </tr>';
        $output .= ' <tr>';
        $output .= '     <td class="col-2" colspan="10">';
        $output .= $reqDropdownString;
        $output .= '     </td>';
        $output .= ' </tr>';

        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="3">Parameter</td>';
        $output .= '     <td colspan="2">Category</td>';
        $output .= '     <td colspan="5">Deliverable</td>';
        $output .= ' </tr>';
        $output .= ' <tr>';
        $output .= '     <td class="col-2" id="edrBox" colspan="3">';
        $output .= $parameterDropdownString;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="2">';
        $output .= $categoryDropdownString;
        $output .= '     </td>';
        $output .= '     <td  class="col-2" colspan="5">';
        $output .= $deliverableTextfieldString;
        $output .= '     </td>';
        $output .= ' </tr>';

        //Section 3 start, end, duration, cost**************************************
        $output .= ' <tr class="row-category"><td class="col-2" colspan="10">Subtask Labor</td></tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td>Start Date</td>';
        $output .= '     <td>End Date</td>';
        $output .= '     <td>Q1 Cost</td>';
        $output .= '     <td>Q2 Cost</td>';
        $output .= '     <td>Q3 Cost</td>';
        $output .= '     <td>Q4 Cost</td>';
        $output .= '     <td>Q1 Hours</td>';
        $output .= '     <td>Q2 Hours</td>';
        $output .= '     <td>Q3 Hours</td>';
        $output .= '     <td>Q4 Hours</td>';
        $output .= ' </tr>';

        $output .= ' <tr class="lightGray">';
        $output .= $this->getTD($startDateTextFieldString);
        $output .= $this->getTD($endDateTextFieldString);
        if (!$this->financialObject) {
            $this->financialObject = $this->getSubtaskFinancials();
        }
        $output .= $this->getTD(getFormInputElement('text', 'q1Cost', "97%", $this->financialObject->curYearDollars[0]));
        $output .= $this->getTD(getFormInputElement('text', 'q2Cost', "97%", $this->financialObject->curYearDollars[1]));
        $output .= $this->getTD(getFormInputElement('text', 'q3Cost', "97%", $this->financialObject->curYearDollars[2]));
        $output .= $this->getTD(getFormInputElement('text', 'q4Cost', "97%", $this->financialObject->curYearDollars[3]));
        $output .= $this->getTD(getFormInputElement('text', 'q1Hours', "97%", $this->financialObject->curYearDuration[0]));
        $output .= $this->getTD(getFormInputElement('text', 'q2Hours', "97%", $this->financialObject->curYearDuration[1]));
        $output .= $this->getTD(getFormInputElement('text', 'q3Hours', "97%", $this->financialObject->curYearDuration[2]));
        $output .= $this->getTD(getFormInputElement('text', 'q4Hours', "97%", $this->financialObject->curYearDuration[3]));
        $output .= ' </tr>';

        //Section 4 Dependencies****************************************************
        $output .= ' <tr class="row-category"><td class="col-2" colspan="10">Subtask Dependencies</td></tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="2">Select a subtask this subtask is dependent on</td>';
        $output .= '     <td colspan="3">Comments</td>';
        $output .= '     <td colspan="5"></td>';
        $output .= ' </tr>';

        $output .= ' <tr>';
        $output .= '     <td class="col-2" colspan="2">';
        $output .= $dependencyDropdownString;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="3">';
        $output .= $commentsTextFieldString;
        $output .= '     </td>';
        $output .= '     <td  class="col-2" colspan="2">';
        $output .= $depAddButtonText;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="3"></td>';
        $output .= ' </tr>';
        $output .= '<tr>';
        $output .= '     <td class="col-2" colspan="6">';
        $output .= $this->getDependencyTable();
        $output .= '</td>';
        $output .= '     <td class="col-2" colspan="4"></td>';
        $output .= ' </tr>';
        //submit button
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="6">';
        $output .= $submitButtonString;
        $output .= '     </td>';
        $output .= '     <td colspan="4">';
        $output .= '      <input type="hidden" name="projectID" value="' . $this->projectID . '">';
        $output .= '      <input type="hidden" name="taskID" value="' . $this->ID . '">';
        $output .= '      <input type="hidden" name="projectStartDate" value="' . $this->projectStartDate . '">';
        $output .= '      <input type="hidden" name="projectEndDate" value="' . $this->projectEndDate . '">';
        $output .= getHiddenField("subtaskId", $this->ID);
        $output .= getHiddenField("submissionType", "edit");
        $output .= '     </td>';
        $output .= ' </tr>';
        $output .= getCloseTag("table");
        $output .= getCloseTag("form");
        return $output;
    }

    function getEditSubtaskForm() {
        $output = "";
        $commentsTextFieldString = getFormInputElementText("text", "commentsTextField", "98%", NULL, NULL, 'commentsTextField');
        $depAddButtonText = getFormInputElementText("button", "depAddButton", "98%", "Add Dependency", "addDependencyRow()");
        $caption = '<caption>Edit Subtask</caption>';
        $dependencyDropdownString = getDependencyDropdownText($this->projectID, $this->ID);
        $reqDropdownString = getGenericDropdownMenuText(getRequirements($this->fy, true), "reqDropdown", NULL, false, NULL, NULL, $this->reqID, NULL, NULL, true); //, "getParametersFromReq(this.value)", "reqDropdown", $this->reqID);
        $categoryDropdownString = getDropDownMenuText(getSubtaskCatergoryArray(), "dropdownCategory", $this->category);
        $deliverableTextfieldString = getFormInputElementText("text", "deliverableTextField", "98%", $this->deliverable);
        $parameterDropdownString = getGenericDropdownMenuText(executeSelect("SELECT * FROM parameter ORDER by name"), "dropdownParameter", "97%", false, NULL, NULL, $this->parameterID);
        //$parameterDropdownString = getParametersFromReqText($this->reqID, true, "getSatFromParameter(this.value)", getParameterNameFromID($this->parameterID));
        $titleString = getFormInputElementText("text", 'titleTextField', '98%', $this->title);
        $descriptionTextFieldString = getFormInputElementText("text", 'descriptionTextField', '98%', $this->description, NULL, 'descriptionTextfield');

        $startDateTextFieldString = getFormInputElementText("text", "startDateTextField", NULL, getDatePickerFormat($this->startDate), NULL, "from");
        $endDateTextFieldString = getFormInputElementText("text", "endDateTextField", NULL, getDatePickerFormat($this->endDate), NULL, "to");
        $durationTextFieldString = getFormInputElementText("text", "durationTextField", '98%', $this->duration, NULL, 'duration');
        $costTextFieldString = getFormInputElementText("text", "costTextField", '98%', $this->proposedCost, "getRate()", 'cost');
        $rate = round($this->proposedCost / $this->duration);
        $submitButtonString = getFormInputElementText("submit", "submit", NULL, "Save Subtask");

        $output .= getFormLinePostWithOnSubmit("createSubtaskForm", "mainPage.php?request=subtask&action=processEditSubtaskSubmit&taskId=$this->ID&projectId=$this->projectID", " validateSubtask(this)");
        //getFormLinePostWithOnSubmit("createSubtaskForm", "subtaskController.php");
        //getStartFormLinePostWithOnSubmit("createSubtaskForm", "test.php", " validateSubtask(this)");
        //Table Start***************************************************************
        $output .= '<table class="width100" cellspacing="1">';
        $colWidth = 100 / 8;
        $output .= '<col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%"><col width="' . $colWidth . '%">';
        $output .= $caption;
        $output .= ' <tr class="row-category"><td class="col-2" colspan="8">Subtask Description</td></tr>';

        //Section 1 Title, Description**********************************************
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="3">Title</td>';
        $output .= '     <td colspan="5">Description</td>';
        $output .= ' </tr>';

        $output .= ' <tr>';
        $output .= '     <td class="col-2" colspan="3">';
        $output .= $titleString;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="5">';
        $output .= $descriptionTextFieldString;
        $output .= '     </td>';
        $output .= ' </tr>';

        //Section 2  Req, Parameter, Category, Deliverable**************************
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="8">Requirement (Ordered By Priority)</td>';
        $output .= ' </tr>';
        $output .= ' <tr>';
        $output .= '     <td class="col-2" colspan="8">';
        $output .= $reqDropdownString;
        $output .= '     </td>';
        $output .= ' </tr>';

        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="3">Parameter</td>';
        $output .= '     <td colspan="2">Category</td>';
        $output .= '     <td colspan="3">Deliverable</td>';
        $output .= ' </tr>';
        $output .= ' <tr>';
        $output .= '     <td class="col-2" id="edrBox" colspan="3">';
        $output .= $parameterDropdownString;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="2">';
        $output .= $categoryDropdownString;
        $output .= '     </td>';
        $output .= '     <td  class="col-2" colspan="3">';
        $output .= $deliverableTextfieldString;
        $output .= '     </td>';
        $output .= ' </tr>';

        //Section 3 start, end, duration, cost**************************************
        $output .= ' <tr class="row-category"><td class="col-2" colspan="8">Subtask Labor</td></tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td>Start Date</td>';
        $output .= '     <td>End Date</td>';
        $output .= '     <td>Effort (Hours)</td>';
        $output .= '     <td>Cost</td>';
        $output .= '     <td>Rate</td>';
        $output .= '     <td colspan="3"></td>';
        $output .= ' </tr>';

        $output .= ' <tr>';
        $output .= '     <td class="col-2">';
        $output .= $startDateTextFieldString;
        $output .= '     </td>';
        $output .= '     <td class="col-2">';
        $output .= $endDateTextFieldString;
        $output .= '     </td>';
        $output .= '     <td  class="col-2">';
        $output .= $durationTextFieldString;
        $output .= '     </td>';
        $output .= '     <td  class="col-2">';
        $output .= $costTextFieldString;
        $output .= ' </td>';
        $output .= '     <td  class="col-2" id="rateBox">';
        $output .= $rate;
        $output .= '</td>';
        $output .= '     <td  class="col-2" colspan="3"></td>';
        $output .= ' </tr>';

        //Section 4 Dependencies****************************************************
        $output .= ' <tr class="row-category"><td class="col-2" colspan="8">Subtask Dependencies</td></tr>';
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="2">Select a subtask this subtask is dependent on</td>';
        $output .= '     <td colspan="3">Comments</td>';
        $output .= '     <td colspan="3"></td>';
        $output .= ' </tr>';

        $output .= ' <tr>';
        $output .= '     <td class="col-2" colspan="2">';
        $output .= $dependencyDropdownString;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="3">';
        $output .= $commentsTextFieldString;
        $output .= '     </td>';
        $output .= '     <td  class="col-2">';
        $output .= $depAddButtonText;
        $output .= '     </td>';
        $output .= '     <td class="col-2" colspan="2"></td>';
        $output .= ' </tr>';
        $output .= '<tr>';
        $output .= '     <td class="col-2" colspan="6">';
        $output .= $this->getDependencyTable();
        $output .= '</td>';
        $output .= '     <td class="col-2" colspan="2"></td>';
        $output .= ' </tr>';
        //submit button
        $output .= ' <tr class ="fieldLabel">';
        $output .= '     <td colspan="6">';
        $output .= $submitButtonString;
        $output .= '     </td>';
        $output .= '     <td colspan="2">';
        $output .= '      <input type="hidden" name="projectID" value="' . $this->projectID . '">';
        $output .= '      <input type="hidden" name="taskID" value="' . $this->ID . '">';
        $output .= '      <input type="hidden" name="projectStartDate" value="' . $this->projectStartDate . '">';
        $output .= '      <input type="hidden" name="projectEndDate" value="' . $this->projectEndDate . '">';
        $output .= getHiddenField("subtaskId", $this->ID);
        $output .= getHiddenField("submissionType", "edit");
        $output .= '     </td>';
        $output .= ' </tr>';
        $output .= getCloseTag("table");
        $output .= getCloseTag("form");
        return $output;
    }

    function processUpdateSubtask() {
        //print_r($_POST);
        //return;        
        $value = $_POST['textFieldPercentComplete'];
        $subtaskId = $_POST['subtaskId'];
        $newStatus = $_POST['subtaskStatusDropdown'];
        $url = $url = $_SERVER['HTTP_REFERER'];
        if (isset($_POST['textFieldComments']) && sizeof($_POST['textFieldComments']) > 0) {
            $originalStatus = $_POST['origStatus'];
            if (strcmp($originalStatus, $newStatus) === 0) {
                $notes = $_POST['textFieldComments'];
            } else {
                $notes = "(Status Change: $originalStatus --> $newStatus) ";
                $notes .= $_POST['textFieldComments'];
            }
            $wbsId = getFieldGivenAnID('subtask', 'subtaskId', $subtaskId, 'wbsID');
            $personId = getPersonIDFromUsername(getCurrentUser());
            $this->insertNotes($notes, 'PI Notes', $wbsId, $personId, $url, 'statusChange');
        }

        $updateResult = executeUpdate("UPDATE subtask set percentComplete=$value, status='$newStatus' WHERE subtaskID=$subtaskId");

        for ($i = 0; $i < 4; $i++) {
            $quarter = $i + 1;
            if (isset($_POST["textFieldHours$i"]) && strlen($_POST["textFieldHours$i"]) > 0) {
                $hours = $_POST["textFieldHours$i"];
                $financialResult = executeUpdate("UPDATE subtaskfinancial set valueActual=$hours WHERE subtaskID=$subtaskId AND quarter=$quarter AND type='hours'");
            }
            if (isset($_POST["textFieldCost$i"]) && strlen($_POST["textFieldCost$i"]) > 0) {
                $dollars = $_POST["textFieldCost$i"];
                $financialResult2 = executeUpdate("UPDATE subtaskfinancial set valueActual=$dollars WHERE subtaskID=$subtaskId AND quarter=$quarter AND type='cost'");
            }
        }
        if ($updateResult) {
            return "location:$url&update=Subtask Update Successful";
        } else {
            return NULL;
        }
    }

    function processUpdateSubtaskPercentCompleteRequest() {
        $value = $_POST['textFieldPercentComplete'];
        $subtaskId = $_POST['subtaskId'];
        $updateResult = executeUpdate("UPDATE subtask set percentComplete=$value WHERE subtaskID=$subtaskId");
        if ($updateResult) {
            $url = $url = $_SERVER['HTTP_REFERER'];
            return "location:$url&update='Percent Update Successful'";
        } else {
            return NULL;
        }
    }

    function processupdateSubtaskFinancialsRequest() {
        //echo print_r($_POST);
        $type = $_POST['subtaskTypeDropdown'];
        $value = $_POST['textFieldFinancial'];
        $subtaskId = $_POST['subtaskId'];
        $quarter = $_POST['subtaskQuarterDropdown'];
        $startDate = $_POST['projectStartDate'];
        $fy = getFYFromMysqlDateFormatStartDate($startDate);
        $updateResult = executeUpdate("UPDATE subtaskfinancial set valueActual=$value WHERE subtaskID=$subtaskId AND quarter=$quarter AND type='$type'");
        if ($updateResult) {
            $url = $url = $_SERVER['HTTP_REFERER'];
            return "location:$url";
        } else {
            return NULL;
        }
    }

    function processEditSubtaskRequestQuarterly() {
        $subtaskTitle = $_POST['titleTextField'];
        $subtaskDescription = $_POST['descriptionTextField'];
        $subtaskDuration = $_POST['durationTextField'];
        $category = $_POST['dropdownCategory'];
        $deliverable = $_POST['deliverableTextField'];

        $startDateDP = $_POST['startDateTextField'];
        $startDate = getMysqlDateFormat($startDateDP);
        $fy = getFYFromMysqlDateFormatStartDate($startDate);
        $endDateDP = $_POST['endDateTextField'];
        $endDate = getMysqlDateFormat($endDateDP);

        $param = $_POST['dropdownParameter'];
        $reqID = $_POST['reqDropdown'];

        //labor stuff   
        $costArray = array();
        $hoursArray = array();
        for ($i = 1; $i < 5; $i++) {
            $subtaskLaborCost += $_POST['q' . $i . 'Cost'];
            $subtaskDuration += $_POST['q' . $i . 'Hours'];
            array_push($hoursArray, $_POST['q' . $i . 'Hours']);
            array_push($costArray, $_POST['q' . $i . 'Cost']);
        }

        //dependency stuff
        $dependencySubtasks = getgenericList("nameField", 20);
        $dependencyComments = getgenericList("commentsField", 20);

        //do an update
        $subTaskID = $_POST['subtaskId'];
        $sqlInsert = "UPDATE subtask SET title='$subtaskTitle',description='$subtaskDescription',duration='$subtaskDuration',
                                             proposedCost='$subtaskLaborCost',parameterID='$param',reqId='$reqID',startDate='$startDate',
                                             endDate='$endDate', category='$category', deliverable='$deliverable' WHERE subtaskId=$subTaskID";

        //echo $sqlInsert . '<br>';
        $result = executeUpdate($sqlInsert);
        if ($result) {
            if ($this->addDependenciesStatic($this->ID, $dependencySubtasks, $dependencyComments)) {
                //return;
                //update the proposed cost/hours
//                if ($this->updateSubtaskProposedFinancialsStatic($this->ID)) {
                if ($this->updateSubtaskFinancialsManual($this->ID, $fy, $costArray, $hoursArray)) {
                    //update the cost of the related task
                    if ($this->updateTaskCostStatic($this->taskID, "proposedCost")) {
                        if ($this->updateTaskPOP2Static($this->taskID)) {
                            if ($this->updateTaskDurationStatic($this->taskID)) {
                                //update the project cost
                                if (!projectModelClass::updateProjectCostStatic($this->projectID, "proposedCost")) {
                                    echo 'error updating project cost <br>';
                                } else {
                                    return "location:mainPage.php?request=subtask&action=viewSubtaskDetails&subtaskId=$this->ID";
                                }
                            } else {
                                echo 'error updating task Duration <br>';
                            }
                        } else {
                            echo 'error updating task POP <br>';
                        }
                    } else {
                        echo 'error updating task cost <br>';
                    }
                } else {
                    echo 'Financial update failed <br>';
                }
            } else {
                echo 'error with dependencies <br>';
            }
        } else {
            echo 'Select projectId failed <br>';
        }
    }

    function processEditSubtaskRequest() {
        $subtaskTitle = $_POST['titleTextField'];
        $subtaskDescription = $_POST['descriptionTextField'];
        $subtaskDuration = $_POST['durationTextField'];
        $category = $_POST['dropdownCategory'];
        $deliverable = $_POST['deliverableTextField'];
        $startDateDP = $_POST['startDateTextField'];
        $startDate = getMysqlDateFormat($startDateDP);
        $fy = getFYFromMysqlDateFormatStartDate($startDate);
        $endDateDP = $_POST['endDateTextField'];
        $endDate = getMysqlDateFormat($endDateDP);
        $param = $_POST['dropdownParameter'];
        //phase 1 sat/sensor are not required so fill in dummy value of 0
        if (isset($_POST['satDropdown'])) {
            $satellite = $_POST['satDropdown'];
            $sensor = $_POST['sensorDropdown'];
        } else {
            $satellite = 0;
            $sensor = 0;
        }
        $reqID = $_POST['reqDropdown'];

        //labor stuff    
        $subtaskLaborCost = 0;
        //new way
        if (isset($_POST['costTextField'])) {
            $subtaskLaborCost = $_POST['costTextField'];
        }
        //old way. Add up all of the individual performers costs
        else {
            $performers = array();
            $laborHours = array();
            $rates = array();
            for ($i = 0; $i < 10; $i++) {
                $nameField = 'nameField' . $i;
                //echo $nameField.'<br>';
                if (isset($_POST['' . $nameField . ''])) {
                    array_push($performers, $_POST['' . $nameField . '']);
                    //echo 'Name: ' . $_POST['' . $nameField . ''] . '<br>';
                    $hourField = 'hourField' . $i;
                    array_push($laborHours, $_POST['' . $hourField . '']);
                    //echo 'Hours: ' . $_POST['' . $hourField . ''] . '<br>';
                    $rateField = 'rateField' . $i;
                    array_push($rates, $_POST['' . $rateField . '']);
                    //echo 'Rate: ' . $_POST['' . $rateField . ''] . '<br>';
                    $subtaskLaborCost += $_POST['' . $hourField . ''] * $_POST['' . $rateField . ''];
                } else {
                    //break;
                }
            }
        }
        $subtaskLaborCost = round($subtaskLaborCost);
        $subtaskLaborHours = $_POST['durationTextField'];

        //dependency stuff
        $dependencySubtasks = getgenericList("nameField", 20);
        $dependencyComments = getgenericList("commentsField", 20);

        //do an update
        $subTaskID = $_POST['subtaskId'];
        $sqlInsert = "UPDATE subtask SET title='$subtaskTitle',description='$subtaskDescription',duration='$subtaskDuration',
                                             proposedCost='$subtaskLaborCost',parameterID='$param',reqId='$reqID',startDate='$startDate',
                                             endDate='$endDate', category='$category', deliverable='$deliverable' WHERE subtaskId=$subTaskID";

        //echo $sqlInsert . '<br>';
        $result = executeUpdate($sqlInsert);
        if ($result) {
            if ($this->addDependenciesStatic($this->ID, $dependencySubtasks, $dependencyComments)) {
                //return;
                //update the proposed cost/hours
                if ($this->updateSubtaskProposedFinancialsStatic($this->ID)) {
                    //update the cost of the related task
                    if ($this->updateTaskCostStatic($this->taskID, "proposedCost")) {
                        if ($this->updateTaskPOP2Static($this->taskID)) {
                            if ($this->updateTaskDurationStatic($this->taskID)) {
                                //update the project cost
                                if (!projectModelClass::updateProjectCostStatic($this->projectID, "proposedCost")) {
                                    echo 'error updating project cost <br>';
                                } else {
                                    return "location:mainPage.php?request=subtask&action=viewSubtaskDetails&subtaskId=$this->ID";
                                }
                            } else {
                                echo 'error updating task Duration <br>';
                            }
                        } else {
                            echo 'error updating task POP <br>';
                        }
                    } else {
                        echo 'error updating task cost <br>';
                    }
                } else {
                    echo 'Financial update failed <br>';
                }
            } else {
                echo 'error with dependencies <br>';
            }
        } else {
            echo 'Select projectId failed <br>';
        }
    }

    function addDependencies($dependencySubtasks, $dependencyComments) {
        //remove all old ones
        $deleteResult = executeDelete("DELETE FROM subtaskdependency WHERE subtaskID=$this->subTaskId");
        if ($deleteResult) {
            for ($i = 0; $i < sizeof($dependencySubtasks); $i++) {
                $depResult = executeInsert("INSERT into subtaskdependency (subtaskID, dependentUponSubtaskID, description) 
                                                       values($this->subTaskId, '$dependencySubtasks[$i]','$dependencyComments[$i]')");
                if (!$depResult) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    function getDependencyTableOld() {
        $output = "";
        $output .= '  <table class="width100" cellspacing="1" id="dependencyTable">';
        $output .= '<caption>Dependency List</caption>';
        $output .= '  <col width="25%"><col width="50%"><col width="12%"><col width="13%">';
        $output .= '    <tr>';
        $output .= '      <td class ="fieldLabel">Subtask</td>';
        $output .= '      <td class ="fieldLabel">Comments</td>';
        $output .= '      <td class ="fieldLabel"></td>';
        $output .= '      <td class ="fieldLabel"></td>';
        $output .= '    </tr>';
        if ($this->dependencies) {
            $i = 0;
            foreach ($this->dependencies as $dependency) {
                $output .= '    <tr id="row' . $i . '">';
                $output .= '      <td class="col-2">';
                $output .= '         <input type="hidden" id="nameField' . $i . '" name="nameField' . $i . '" value="' . $dependency->subtaskId . '">' . $dependency->title . '</td>';
                $output .= '      <td class="col-2">';
                $output .= '          <input type="hidden" id="commentsField' . $i . '" name="commentsField' . $i . '" value="' . $dependency->description . '">' . $dependency->description . '</td>';
                $output .= '<td class="col-2">';
                $output .= getFormInputElement("button", $i, NULL, "Edit", "editDependencyRow(this.name)", NULL);
                $output .= '</td class ="fieldLabel">';
                $output .= '      <td class ="col-2">';
                $output .= getFormInputElement("button", $i, NULL, "Remove", "removeDependencyRow(this.name)", NULL);
                $output .= '</td>';
                $output .= '    </tr>';
                $i++;
            }
        }
        $output .= getCloseTag("table");
        return $output;
    }

    protected function getSubtaskLabor() {
        $array = array();
        $subtaskLaborResult = executeSelect("SELECT subtaskLaborId FROM subtasklabor WHERE subtaskId=$this->ID");
        if ($subtaskLaborResult) {
            while ($row = mysqli_fetch_array($subtaskLaborResult)) {
                $stLaborObj = new subtaskLabor($row);
                array_push($array, $stLaborObj);
            }
        }
        return $array;
    }

    /**
     * This deletes the subtask labor, subtask and wbs
     * @param type $subtaskId
     * @return boolean
     */
    function deleteSubtask() {

        //st labor
        executeDelete("DELETE FROM subtasklabor WHERE subtaskID=$this->ID");
        //dependencies
        executeDelete("DELETE FROM subtaskdependency WHERE subtaskID=$this->ID");
        //delete subtask financials
        executeDelete("DELETE FROM subtaskfinancial WHERE subtaskID=$this->ID");
        //subtask
        executeDelete("DELETE FROM subtask WHERE subtaskId=$this->ID");
        //wbs
        executeDelete("DELETE FROM wbs WHERE wbsId=$this->wbsID");

        //update project if this was the only subtask under a task
        if (!projectModelClass::doesEachTaskHaveASubtask($this->projectID)) {
            projectModelClass::updateProjectStatusStatic($this->projectID, 'taskSubmit');
        }

        //update cost
        commonModel::updateTaskCost($this->taskID, "proposedCost");
        projectModelClass::updateProjectCostStatic($this->projectID, 'proposedCost');

        //update task effort
        taskModelClass::updateTaskDurationStatic($this->taskID);

        //update task POP
        taskModelClass::updateTaskPOP2Static($this->taskID);
        return "location:mainPage.php?request=task&projectId=$this->projectID&taskId=$this->taskID&action=viewTaskDetails&update=Subtask deletion Successful";
    }

    function deleteSubtaskFinancials() {
        $stfResult = executeSelect("SELECT * FROM subtaskfinancial WHERE subtaskID=$this->subTaskId");
        if ($stfResult && $stfResult->num_rows > 0) {
            while ($row = mysqli_fetch_array($stfResult)) {
                $stfID = $row['subtaskFinancialID'];
                $stfDeleteResult = executeDelete("DELETE FROM subtaskfinancial WHERE subtaskFinancialID=$stfID");
            }
        }
    }

    /**
     * This should be called when a subtask is created or edited
     * @param type $subtaskID
     */
    function updateSubtaskProposedFinancials() {
        //query the cost/hours for the subtask
        $row = mysqli_fetch_array(executeSelect("SELECT * FROM subtask WHERE subtaskID=$this->subTaskId"));
        $startDate = $row['startDate'];
        $endDate = $row['endDate'];
        $cost = $row['proposedCost'];
        $hours = $row['duration'];
        $fy = getFYFromMysqlDateFormatStartDate($startDate);
        $financialObject = new financialClass($startDate, $endDate, $cost, $hours, $fy);
        $financialObject->initialize();
        //delete all existing entries and just insert new ones.
        deleteSubtaskFinancials($this->subTaskId);
        //insert an entry for each quarter (quarter1=index0, quarter2=index1 ..)
        for ($i = 0; $i < 4; $i++) {
            //see if it exists
            $curQuarter = $i + 1;
            $curQuarterHours = $financialObject->curYearDuration[$i];
            $curQuarterCost = $financialObject->curYearDollars[$i];
            if ($curQuarterCost != 0) {
                $stfResult = executeSelect("SELECT * FROM subtaskfinancial WHERE subtaskID=$this->subTaskId AND fy=$fy AND quarter=$curQuarter");
                if ($stfResult && $stfResult->num_rows > 0) {
                    //update
                    echo "update <br>";
                    $updateHoursResult = executeUpdate("UPDATE subtaskfinancial SET valueProposed=$curQuarterHours WHERE subtaskID=$this->subTaskId AND fy=$fy AND quarter=$curQuarter AND type='hours'");
                    $updateCostResult = executeUpdate("UPDATE subtaskfinancial SET valueProposed=$curQuarterCost WHERE subtaskID=$this->subTaskId AND fy=$fy AND quarter=$curQuarter AND type='cost'");
                    if (!$updateHoursResult || !$updateCostResult) {
                        return false;
                    }
                } else {
                    //insert 
                    //echo "Insert <br>";
                    $insertHoursResult = executeUpdate("INSERT into subtaskfinancial (valueProposed, subtaskID, fy, quarter, type) 
                                                        values ($curQuarterHours,$this->subTaskId,$fy,$curQuarter, 'hours')");
                    $insertCostResult = executeUpdate("INSERT into subtaskfinancial (valueProposed, subtaskID, fy, quarter, type) 
                                                        values ($curQuarterCost,$this->subTaskId,$fy,$curQuarter, 'cost')");
                    if (!$insertHoursResult || !$insertCostResult) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    function getSubtaskNotes($type, $subtype = null, $value = NULL) {
        return executeSelect("SELECT n.* FROM notes n, subtask st WHERE st.subtaskID=$this->subTaskId AND st.wbsID=n.wbsId and type='$type'");
    }

    function setSubtaskFinancials($subtaskStartDate, $subtaskEndDate, $cost, $hours, $fy, $actual) {

        $obj = new financialClass($subtaskStartDate, $subtaskEndDate, $cost, $hours, $fy);
        $obj->initialize();
        $valueType = 'valueActual';
        if (!$actual) {
            $valueType = 'valueProposed';
        }
        //4 quarters
        for ($i = 0; $i < 4; $i++) {
            if ($obj->curYearDollars[$i] != 0) {
                $quarter = $i + 1;
                //hours first
                $financialExistsResult = executeSelect("SELECT * FROM subtaskfinancial WHERE subtaskID=$this->subTaskId AND quarter=$quarter AND fy=$fy and type='hours'");
                if ($financialExistsResult) {
                    //exists so do an update query
                    $row = mysqli_fetch_array($financialExistsResult);
                    $financialID = $row['subtaskFinancialID'];
                    $setFinancialsQuery = "UPDATE subtaskfinancial ($valueType) values ($obj->curYearDollars[$i]) WHERE subtaskFinancialID=$financialID";
                } else {
                    //does not exist so do an insert query
                    $setFinancialsQuery = "INSERT into subtaskfinancial (subtaskID,fy,quarter,type,$valueType) values ($this->subTaskId,$fy,$quarter,'hours',$obj->curYearDollars[$i])";
                }
                $financialExecuteQuery = executeInsert($setFinancialsQuery);
                if (!$financialExecuteQuery) {
                    return false;
                }
                echo $obj->curYearDuration[$i];
                echo " cost: ";
                echo $obj->curYearDollars[$i];
                echo "<br>";
            } else {
                
            }
        }
        return true;
    }

    function getSubtaskFinancials() {
        $obj = new financialClass(NULL, NULL, NULL, NULL, NULL);
        $obj->initializeFillManually();
        $obj->taskID = $this->taskID;
        $stResult = executeSelect("SELECT * FROM subtaskfinancial WHERE subtaskID=$this->ID");
        while ($row = mysqli_fetch_array($stResult)) {
            $quarter = $row['quarter'];
            $type = $row['type']; //hours or $$$
            $valueProposed = $row['valueProposed'];
            $valueActual = $row['valueActual'];
            $proposedRebaseline = $row['proposedRebaseline'];
            if (strcmp($type, 'hours') === 0) {
                $obj->curYearDuration[$quarter - 1] = $valueProposed;
                $obj->actualDuration[$quarter - 1] = $valueActual;
                $obj->rebaselineDuration[$quarter - 1] = $proposedRebaseline;
            } else if (strcmp($type, 'cost') === 0) {
                $obj->curYearDollars[$quarter - 1] = $valueProposed;
                $obj->actualDollars[$quarter - 1] = $valueActual;
                $obj->rebaselineDollars[$quarter - 1] = $proposedRebaseline;
            } else {
                //milestones
                $obj->actualMilestones[$quarter - 1] = "1";
                $obj->rebaselineMilestones[$quarter - 1] = $proposedRebaseline;
            }
        }
        return $obj;
    }

    function getDependencies() {
        $array = array();
        $stDependencyResult = executeSelect("SELECT * FROM subtaskdependency WHERE subtaskID=$this->ID");
        while ($row = mysqli_fetch_array($stDependencyResult)) {
            $dependentOnSubtaskID = $row['dependentUponSubtaskID'];
            $description = $row['description'];
            $dependentSubtaskTitle = getFieldGivenAnID('subtask', 'subtaskID', $dependentOnSubtaskID, 'title');
            $stDepObj = new subtaskDependency($dependentOnSubtaskID, $description, $dependentSubtaskTitle);
            array_push($array, $stDepObj);
        }
        return $array;
    }

    //static
    static function addDependenciesStatic($subTaskId, $dependencySubtasks, $dependencyComments) {
        //remove all old ones
        $deleteResult = executeDelete("DELETE FROM subtaskdependency WHERE subtaskID=$subTaskId");
        if ($deleteResult) {
            for ($i = 0; $i < sizeof($dependencySubtasks); $i++) {
                //echo $dependencySubtasks[$i] . '<br>';
                $depResult = executeInsert("INSERT into subtaskdependency (subtaskID, dependentUponSubtaskID, description) 
                                                       values($subTaskId, '$dependencySubtasks[$i]','$dependencyComments[$i]')");
                if (!$depResult) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    static function updateSubtaskFinancialsManual($subtaskID, $fy, $costArray, $hourArray) {
        for ($i = 0; $i < 4; $i++) {
            //see if it exists
            $curQuarter = $i + 1;
            $stfResult = executeSelect("SELECT * FROM subtaskfinancial WHERE subtaskID=$subtaskID AND fy=$fy AND quarter=$curQuarter");
            if ($stfResult && $stfResult->num_rows > 0) {
                //update
                $updateHoursResult = executeUpdate("UPDATE subtaskfinancial SET valueProposed=$hourArray[$i] WHERE subtaskID=$subtaskID AND fy=$fy AND quarter=$curQuarter AND type='hours'");
                $updateCostResult = executeUpdate("UPDATE subtaskfinancial SET valueProposed=$costArray[$i] WHERE subtaskID=$subtaskID AND fy=$fy AND quarter=$curQuarter AND type='cost'");
                if (!$updateHoursResult || !$updateCostResult) {
                    return false;
                }
            } else {
                //insert                 
                $insertHoursResult = executeUpdate("INSERT into subtaskfinancial (valueProposed, subtaskID, fy, quarter, type) 
                                                        values ($hourArray[$i],$subtaskID,$fy,$curQuarter, 'hours')");
                $insertCostResult = executeUpdate("INSERT into subtaskfinancial (valueProposed, subtaskID, fy, quarter, type) 
                                                        values ($costArray[$i],$subtaskID,$fy,$curQuarter, 'cost')");
                if (!$insertHoursResult || !$insertCostResult) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * This should be called when a subtask is created or edited
     * @param type $subtaskID
     */
    static function updateSubtaskProposedFinancialsStatic($subtaskID) {
        //query the cost/hours for the subtask
        $row = mysqli_fetch_array(executeSelect("SELECT * FROM subtask WHERE subtaskID=$subtaskID"));
        $startDate = $row['startDate'];
        $endDate = $row['endDate'];
        $cost = $row['proposedCost'];
        $hours = $row['duration'];
        $fy = getFYFromMysqlDateFormatStartDate($startDate);
        $financialObject = new financialClass($startDate, $endDate, $cost, $hours, $fy);
        $financialObject->initialize();
        //delete all existing entries and just insert new ones.
        subtaskModelClass::deleteSubtaskFinancialsStatic($subtaskID);
        //insert an entry for each quarter (quarter1=index0, quarter2=index1 ..)
        for ($i = 0; $i < 4; $i++) {
            //see if it exists
            $curQuarter = $i + 1;
            $curQuarterHours = $financialObject->curYearDuration[$i];
            $curQuarterCost = $financialObject->curYearDollars[$i];
            //if ($curQuarterCost != 0) {
            $stfResult = executeSelect("SELECT * FROM subtaskfinancial WHERE subtaskID=$subtaskID AND fy=$fy AND quarter=$curQuarter");
            if ($stfResult && $stfResult->num_rows > 0) {
                //update
                echo "update <br>";
                $updateHoursResult = executeUpdate("UPDATE subtaskfinancial SET valueProposed=$curQuarterHours WHERE subtaskID=$subtaskID AND fy=$fy AND quarter=$curQuarter AND type='hours'");
                $updateCostResult = executeUpdate("UPDATE subtaskfinancial SET valueProposed=$curQuarterCost WHERE subtaskID=$subtaskID AND fy=$fy AND quarter=$curQuarter AND type='cost'");
                if (!$updateHoursResult || !$updateCostResult) {
                    return false;
                }
            } else {
                //insert 
                //echo "Insert <br>";
                $insertHoursResult = executeUpdate("INSERT into subtaskfinancial (valueProposed, subtaskID, fy, quarter, type) 
                                                        values ($curQuarterHours,$subtaskID,$fy,$curQuarter, 'hours')");
                $insertCostResult = executeUpdate("INSERT into subtaskfinancial (valueProposed, subtaskID, fy, quarter, type) 
                                                        values ($curQuarterCost,$subtaskID,$fy,$curQuarter, 'cost')");
                if (!$insertHoursResult || !$insertCostResult) {
                    return false;
                }
            }
            // }
        }
        return true;
    }

    static function deleteSubtaskFinancialsStatic($subtaskID) {
        $stfResult = executeSelect("SELECT * FROM subtaskfinancial WHERE subtaskID=$subtaskID");
        if ($stfResult && $stfResult->num_rows > 0) {
            while ($row = mysqli_fetch_array($stfResult)) {
                $stfID = $row['subtaskFinancialID'];
                $stfDeleteResult = executeDelete("DELETE FROM subtaskfinancial WHERE subtaskFinancialID=$stfID");
            }
        }
    }

    static function getNewSubtaskHeader() {
        $output = getNewHtmlUpToMeta();
        $output .= getJavascriptFileLine("js/populateDropdown.js");
        $output .= getJavascriptFileLine("js/addRowToTable.js");
        $output .= getJavascriptFileLine("js/formValidation.js");
        $output .= getMantisCSSLine();
        $start = $_POST['projectStartDate'];
        $end = $_POST['projectEndDate'];
        //getDatepickerStuff();
        //getDatepickerStuffRestrictDates($start, $end, true);
        $output .= getSubtaskDatepicker($start, $end, true, true);
        $output .= getTitle("Subtask");
        $output .= getCloseTag("head");
        $output .= getOpenTag("body");
        $output .= getLogoLine();
        $output .= getLoggedInAsLine();
        $output .= getPiMenu();
        $output .= '<br>';
        $output .= '<br>';
        return $output;
    }

    /**
     * This deletes the subtask labor, subtask and wbs
     * @param type $subtaskId
     * @return boolean
     */
    static function deleteSubtaskStatic($subtaskId) {

        //delete subtask labor
        $subtaskLaborResult = executeSelect("SELECT subtaskLaborId FROM subtasklabor WHERE subtaskId=$subtaskId");
        if ($subtaskLaborResult) {
            while ($row = mysqli_fetch_array($subtaskLaborResult)) {
                $laborId = $row['subtaskLaborId'];
                $slDelete = executeInsert("DELETE FROM subtasklabor WHERE subtaskLaborId=$laborId");
                if (!$slDelete) {
                    echo 'Error deleting subtaskLabor <br>';
                }
            }
        }
        //subtask financials
        $deleteSubtaskFinancialsResult = executeDelete("DELETE FROM subtaskfinancial WHERE subtaskID=$subtaskId");

        //subtask
        $wbsResult = executeSelect("SELECT wbsID FROM subtask WHERE subtaskId=$subtaskId");
        echo "SELECT wbsID FROM subtask WHERE subtaskId=$subtaskId <br>";
        if ($wbsResult) {
            $row = mysqli_fetch_array($wbsResult);
            $wbsId = $row['wbsID'];
            $taskDelete = executeInsert("DELETE FROM subtask WHERE subtaskId=$subtaskId");
            if ($taskDelete) {
                $wbsDelete = executeInsert("DELETE FROM wbs WHERE wbsId='$wbsId'");
                if ($wbsDelete) {
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            echo "error selecting wbs for subtask $subtaskId<br>";
        }
    }

}

?>
